package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuMapper;
import com.itheima.dao.RoleDao;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuMapper;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	RoleDao roleDao;

	@Autowired
	UserDao userDao;

	@Autowired
	MenuMapper menuMapper;
	/*查询所有角色*/

	@Override
	public List<Role> findAllRoles() {
		return roleDao.findAllRoles();
	}

	@Override
	public PageResult findAll(QueryPageBean queryPageBean) {
		PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
		Page<Role> page = roleDao.findAll(queryPageBean.getQueryString());
		return new PageResult(page.getTotal(), page);
	}


    @Override
    public void add(Role role,Integer[] checkitemIds,Integer[] menukitemIds) {
        roleDao.add(role);
        for (Integer checkitemId : checkitemIds) {
            roleDao.addRolePermission(role.getId(),checkitemId);
        }
        for (Integer menukitemId : menukitemIds) {
            menuMapper.add_role_menu(role.getId(),menukitemId);
        }
    }

	@Override
	public Role findById(Integer id) {
		return roleDao.findById(id);
	}

	@Override
	public Integer[] findR_P(Integer id) {
		return roleDao.findR_P(id);
	}

	@Override
	public void update(Role role,Integer[] checkitemIds,Integer[] menukitemIds ){
		roleDao.edit(role);

		roleDao.delPermission(role.getId());
		for (Integer checkitemId : checkitemIds) {
			roleDao.addRolePermission(role.getId(),checkitemId);
		}
		menuMapper.delMenu(role.getId());
		for (Integer menukitemId : menukitemIds) {
			menuMapper.add_role_menu(role.getId(),menukitemId);
		}
	}

	@Override
	public void del(Integer id) {
		//查询角色表有没有被用户表关联
		long num2 = userDao.get_user_role(id);
		if (num2 > 0){
			throw new RuntimeException("您要删除的角色有外键关联不可以删除");
		}
		//查询角色表有没有关联权限表
		long num = roleDao.get_role_permission(id);
		if (num > 0){
			roleDao.delPermission(id);
		}
		menuMapper.delMenu(id);

		roleDao.del(id);
	}
}
